﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Storage.Core.Caching;
using Storage.Core.Data;
using Storage.Entities;
using Storage.Mapping.SysUserToken;
using Storage.Mapping;

namespace Storage.Services.SysUserToken
{
    public class SysUserTokenService : ISysUserTokenService
    {
        //缓存key
        private const string MODEL_KEY = "Storage.Admin.logged_token_{0}";

        private IRepository<Entities.SysUserToken> _sysUserTokenRepository;
        private ICacheManager _cacheManager;

        public SysUserTokenService(IRepository<Entities.SysUserToken> sysUserTokenRepository,
            ICacheManager cacheManager)
        {
            this._sysUserTokenRepository = sysUserTokenRepository;
            this._cacheManager = cacheManager;
        }

        /// <summary>
        /// 已登录用户获取token
        /// 获取到后并缓存
        /// </summary>
        /// <param name="tokenId"></param>
        /// <returns></returns>
        public SysUserTokenMapping getLoggedToken(Guid tokenId)
        {
            string key = String.Format(MODEL_KEY, tokenId);
            return _cacheManager.get<SysUserTokenMapping>(key, () =>
            {
                var item = _sysUserTokenRepository.getById(tokenId);
                if (item != null)
                    return item.toModel();
                return null;
            });
        }

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="token"></param>
        public void insertToken(Entities.SysUserToken token)
        {
            var list = _sysUserTokenRepository.Table.Where(o => o.SysUserId == token.SysUserId).ToList();
            if (list.Any())
                foreach (var del in list)
                {
                    _sysUserTokenRepository.Entities.Remove(del);
                    removeCache(del.Id);
                }
            _sysUserTokenRepository.insert(token);
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="tokenId"></param>
        public void removeCache(Guid tokenId)
        {
            _cacheManager.remove(String.Format(MODEL_KEY, tokenId));
        }

        /// <summary>
        /// 从数据获取所有的数据
        /// </summary>
        /// <returns></returns>
        public List<SysUserTokenMapping> getAll()
        {
            return _sysUserTokenRepository.Table.OrderByDescending(o => o.SysUser.LastLoginTime)
                .Select(item => new SysUserTokenMapping()
                {
                    Id = item.Id,
                    ExpireTime = item.ExpireTime,
                    SysUserId = item.SysUserId,
                    SysUser = new Mapping.SysUser.SysUserMapping()
                    {
                        Id = item.SysUserId,
                        Name = item.SysUser.Name,
                        Account = item.SysUser.Account,
                        LastLoginTime = item.SysUser.LastLoginTime,
                        LastIpAddress = item.SysUser.LastIpAddress,
                        LastActivityTime = item.SysUser.LastActivityTime,
                        IsAdmin = item.SysUser.IsAdmin
                    }
                }).ToList();
        }

        /// <summary>
        /// 令用户退出登陆
        /// </summary>
        /// <param name="tokenId"></param>
        public void logOut(Guid tokenId)
        {
            var item = _sysUserTokenRepository.getById(tokenId);
            if (item == null)
                return;
            _sysUserTokenRepository.delete(item);
            removeCache(tokenId);
        }

    }
}
